package cycling.taxi.com.ui.fragment;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.baidu.mapapi.utils.OpenClientUtil;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.baidu.mapapi.utils.route.RouteParaOption;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cycling.taxi.com.IConstants;

import cycling.taxi.com.R;
import cycling.taxi.com.entity.BusinessCheckpoint;
import cycling.taxi.com.entity.Tips;
import cycling.taxi.com.eventbus.SetTime;
import cycling.taxi.com.request.Config;
import cycling.taxi.com.request.RM;
import cycling.taxi.com.request.RequestBean;
import cycling.taxi.com.request.RequestCallback;
import cycling.taxi.com.request.RequestParams;
import cycling.taxi.com.request.RequestUtil;
import cycling.taxi.com.ui.activity.FixlocationlistActivity;
import cycling.taxi.com.utils.LogUtil;
import cycling.taxi.com.utils.SPUtil;
import cycling.taxi.com.utils.ToastUtil;
import cycling.taxi.com.utils.Urls;

/**
 * Created by Administrator on 2017/5/4.
 */
public class FixFrgt extends Fragment implements RequestCallback ,View.OnClickListener{
    @InjectView(R.id.bmapView_fix)
    MapView mMapView = null;
    @InjectView(R.id.more)
    TextView textView;
    @InjectView(R.id.frgt_bottom)
    RelativeLayout fragbottom;
    @InjectView(R.id.website_tv_fix)
    TextView website_tv;
@InjectView(R.id.distance_f)
TextView distance;
    @InjectView(R.id.address_fix)
    TextView address;
    @InjectView(R.id.loc)
    ImageView loc;

    private BaiduMap mBaiduMap;
    private ArrayList<BusinessCheckpoint>data;
    LatLng pointgps;
    LatLng ptStart=null;
    private LocationClient mLocationClient;
    LatLng point;
    private PopupWindow mPopupWindow;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_fix_frgt, null);

        ButterKnife.inject(this,view);
        SDKInitializer.initialize(this.getContext());
        initMap();
        distance();
        EventBus.getDefault().register(this);
        mLocationClient = new LocationClient(this.getContext());
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);//扫描时间
        MyLocationListener myListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myListener);// //注册监听函数
        mLocationClient.setLocOption(option);
        mLocationClient.start();
        InitpopupView(view);
    //    initData();
     //   initUI();

        return view;
    }
    public void InitpopupView(View view){
      //  View popupView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_popupwindow, null);
      //  mPopupWindow = new PopupWindow(popupView, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);

     //  mPopupWindow.setTouchable(true);
        mPopupWindow=new MapPopWindow(getActivity(),ptStart,pointgps);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
    }
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //Receive Location
            //经纬度
            if(ptStart==null){
            double lati = location.getLatitude();
            double longa = location.getLongitude();
            //打印出当前位置
            ptStart=new LatLng(lati,longa);}

        }
    }

    public void initData(){
        //LatLng pointgps = new LatLng(25.271221853027, 110.32083240992);
        CoordinateConverter converter  = new CoordinateConverter();
        converter.from(CoordinateConverter.CoordType.GPS);
        converter.coord(pointgps);
        point = converter.convert();
    }
    public void distance(){
        RequestParams params = new RequestParams.Builder()
                .build();

        //开始请求发送数据到服务器服务器
        RequestQueue requestQueue = Volley.newRequestQueue(this.getActivity());
        String url = Urls.getFixdistance()+"?sum=1&beanJson="+ SPUtil.getInstance().getData("beanJson").replace(" ","%20");//回去api路径
        RequestUtil.requestData(requestQueue,
                IConstants.FIXDISTANCE,
                url,
                RM.GET,
                RequestBean.class,
                params,
                this);
    }
    public void initMap(){
        mBaiduMap = mMapView.getMap();
        //地图上比例尺
        mMapView.showScaleControl(false);
        // 隐藏缩放控件
        mMapView.showZoomControls(false);
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.getUiSettings().setAllGesturesEnabled(false);
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            //地图单击事件回调函数
            public void onMapClick(LatLng point) {
              // startToAty(TestActivity.class,point);
               // startRoutePlanDriving_fixfrgt();
                //高德
//                Intent intent = new Intent();
//                intent.setAction(Intent.ACTION_VIEW);
//                intent.addCategory(Intent.CATEGORY_DEFAULT);
//                Uri uri = Uri.parse("androidamap://route/plan/?slat=39.92848272&slon=116.39560823&did=BGVIS2&dlat=39.98848272&dlon=116.47560823&dev=0&t=3");
//                intent.setData(uri);
//                intent.setPackage("com.autonavi.minimap");
//                startActivity(intent);
                //////////////百度
//                Intent i1 = new Intent();
//                if(isAvilible(getContext(),"com.baidu.BaiduMap")) {
//                    i1.setData(Uri.parse("baidumap://map/direction?origin=name:对外经贸大学|latlng:39.98871,116.43234&destination=name:西直门&mode=riding&sy=3&index=0&target=1"));
//                    startActivity(i1);
//                }else{//未安装
//                    //market为路径，id为包名
//                    //显示手机上所有的market商店
//                    Toast.makeText(getContext(), "您尚未安装百度地图", Toast.LENGTH_LONG).show();
//                    Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
//                    i1 = new Intent(Intent.ACTION_VIEW, uri);
//                    startActivity(i1);
//                }
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }

        });
        fragbottom.setOnClickListener(this);
        loc.setOnClickListener(this);
        //定义Maker坐标点110.32083240992,25.271221853027
    }

    public static boolean isAvilible(Context context, String packageName){
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if(packageInfos != null){
            for(int i = 0; i < packageInfos.size(); i++){
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }
    public  void startRoutePlanDriving_fixfrgt() {

       // LatLng ptEnd = new LatLng(25.28693,110.322239);

        // 构建 route搜索参数
        RouteParaOption para = new RouteParaOption()
                .startPoint(ptStart)
                .endPoint(pointgps);
        try {
            BaiduMapRoutePlan.openBaiduMapDrivingRoute(para, this.getContext());
        } catch (Exception e) {
            e.printStackTrace();
            showDialog();
        }

    }
    /**
     * 提示未安装百度地图app或app版本过低
     */
    public void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
        builder.setMessage("您尚未安装百度地图app或app版本过低，点击确认安装？");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                OpenClientUtil.getLatestBaiduMapApp(getActivity());
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.create().show();

    }
    public void initUI(){


        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.ic_line_stop_red);
        OverlayOptions option = new MarkerOptions().position(pointgps).icon(bitmap);//构建MarkerOption，用于在地图上添加Marker
        mBaiduMap.addOverlay(option);//在地图上添加Marker，并显示
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().target(pointgps).zoom(15).build()));



    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        EventBus.getDefault().unregister(this);
        mLocationClient.stop();
    }
    @Override
    public void requestSuccess(RequestBean bean, Config config) {
        LogUtil.e(bean.beanJson);
        data = new Gson().fromJson(bean.beanJson,new TypeToken<List<BusinessCheckpoint>>(){}.getType());
        String gps[]=data.get(0).getGps().split(",");
        double lantitude=Double.parseDouble(gps[1]);
        double longtitude=Double.parseDouble(gps[0]);
        pointgps= new LatLng(lantitude,longtitude);
      //  initData();
        initUI();
        if(distance!=null){
            distance.setText(String.valueOf(Double.parseDouble(data.get(0).getDistance()) / 10));
            address.setText(data.get(0).getAddress());
            website_tv.setText(data.get(0).getName());
        }
        //LogUtil.e(gpst);

    }

    @Override
    public void requestFail(RequestBean bean, Config config) {

    }

    @Override
    public void requestTokenInvalid(String requestTag, Config config) {

    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.frgt_bottom){
            Intent intent = new Intent(this.getActivity(), FixlocationlistActivity.class);
            intent.putExtra("ptStart",ptStart);
            startActivity(intent);
        }
        if(v.getId()==R.id.loc){
          //  startRoutePlanDriving_fixfrgt();
//            Intent intent = new Intent(this.getActivity(), FindMap.class);
//            startActivity(intent);
            mPopupWindow.showAsDropDown(v);
        }

    }
    @Subscribe
    public void onEvent(SetTime time){
       // LogUtil.d(time.getTime().getLastTime());
       Double Long= Double.parseDouble(time.getTime().getLongitude());
        Double Lan=Double.parseDouble(time.getTime().getLatitude());
       ptStart=new LatLng(Lan,Long);
       // website_tv.setText(ptStart.toString());
    }
    public class MapPopWindow extends PopupWindow {

        private View mMenuView;
        private TextView baidumap, clear;

        public MapPopWindow(final Activity context, final LatLng start, final LatLng end) {
            super(context);
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mMenuView = inflater.inflate(R.layout.layout_popupwindow, null);
            baidumap = (TextView) mMenuView.findViewById(R.id.baidumap);
            clear = (TextView) mMenuView.findViewById(R.id.clear);
            //取消按钮
            clear.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    //销毁弹出框
                    dismiss();
                }
            });
            //设置按钮监听
            baidumap.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startRoutePlanDriving_fixfrgt();
                    //   BaiduMapRoutePlan.openBaiduMapDrivingRoute(para,context);
                }
            });
            //设置SelectPicPopupWindow的View
            this.setContentView(mMenuView);
            //设置SelectPicPopupWindow弹出窗体的宽
            this.setWidth(ActionBar.LayoutParams.WRAP_CONTENT);
            //设置SelectPicPopupWindow弹出窗体的高
            this.setHeight(ActionBar.LayoutParams.WRAP_CONTENT);
            //设置SelectPicPopupWindow弹出窗体可点击
            this.setFocusable(true);
//        //设置SelectPicPopupWindow弹出窗体动画效果
//        this.setAnimationStyle(R.style.AnimBottom);
//        //实例化一个ColorDrawable颜色为半透明
//        ColorDrawable dw = new ColorDrawable(0xb0000000);
//        //设置SelectPicPopupWindow弹出窗体的背景
//        this.setBackgroundDrawable(dw);
            //mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
//        mMenuView.setOnTouchListener(new View.OnTouchListener() {
//
//            public boolean onTouch(View v, MotionEvent event) {
//
//                int height = mMenuView.findViewById(R.id.pop_layout).getTop();
//                int y=(int) event.getY();
//                if(event.getAction()==MotionEvent.ACTION_UP){
//                    if(y<height){
//                        dismiss();
//                    }
//                }
//                return true;
//            }
//        });

        }
    }
}
